<template>
  <div id="indexMap">
    <div id="map"></div>
    <index-query></index-query>
  </div>
</template>

<script>
window.CESIUM_BASE_URL = "/";
import * as Cesium from "cesium";
import "cesium/Build/Cesium/Widgets/widgets.css";
import IndexQuery from "./IndexQuery.vue";
import { ipcRenderer } from "electron";
export default {
  data() {
    return {
      img: [],
      wkt: "",
    };
  },
  components: { IndexQuery },
  name: "CesiumDemo",
  mounted() {
    Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2YzRjYmVkZS1mYzVkLTRhNzQtOWQxNS00ODhkYjNiMTVhZjMiLCJpZCI6ODg4MCwiaWF0IjoxNjI5MDg0MjU5fQ.HjR32IeXm9JIf43_sIzuRBeIeJyf01VBLgeCdnTFyJw'
    Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(
      115 - 1,
      36 - 1,
      115 + 1,
      36 + 1
    );

    const viewer = new Cesium.Viewer("map", {
      shadows: false,
      terrainShadows: Cesium.ShadowMode.RECEIVE_ONLY,
      shouldAnimate: false,
      animation: false, //是否创建动画小器件，左下角仪表
      baseLayerPicker: false, //是否显示图层选择器
      fullscreenButton: false, //是否显示全屏按钮
      geocoder: false, //是否显示geocoder小器件，右上角查询按钮
      homeButton: false, //是否显示Home按钮
      infoBox: false, //是否显示信息框
      sceneModePicker: false, //是否显示3D/2D选择器
      selectionIndicator: true, //是否显示选取指示器组件
      timeline: false, //是否显示时间轴
      sceneMode: Cesium.SceneMode.SCENE3D, //设定3维地图的默认场景模式:Cesium.SceneMode.SCENE2D、Cesium.SceneMode.SCENE3D、Cesium.SceneMode.MORPHING
      navigationHelpButton: false, //是否显示右上角的帮助按钮
      scene3DOnly: true, //如果设置为true，则所有几何图形以3D模式绘制以节约GPU资源
      navigationInstructionsInitiallyVisible: false,
      showRenderLoopErrors: false, //是否显示渲染错误
    });

    viewer.imageryLayers.removeAll();
    viewer.imageryLayers.addImageryProvider(
      new Cesium.UrlTemplateImageryProvider({
        url: "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png",
      })
    );

    viewer._cesiumWidget._creditContainer.style.display = "none";
    viewer.scene.globe.depthTestAgainstTerrain = true;
    viewer.scene.moon.show = false;
    viewer.scene.fog.enabled = false;
    viewer.scene.sun.show = false;
    viewer.scene.skyBox.show = false;
    viewer.resolutionScale = 1.0;
    viewer.selectionIndicator.destroy();
    viewer.scene.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(119.5, 35.5, 200000),
      duration: 5,
      complete: () => {
        this.$message({
          message: "欢迎使用下载器",
          type: "success",
          Headers,
        });
      },
    });

    ipcRenderer.on("sendBoxtoMap", (e, box) => {
      viewer.dataSources.removeAll();
      const datasource = viewer.dataSources.add(
        Cesium.GeoJsonDataSource.load(box, {
          fill: Cesium.Color.WHITE.withAlpha(0.1),
          clampToGround: true,
        })
      );
      viewer.flyTo(datasource);
    });

    ipcRenderer.on("sendImgtoMap", (e, img) => {
      viewer.entities.removeAll();
      img.map((element, index) => {
        let imgPath = "http://36.112.130.153:7777/imageApi" + element.thumbfilelocation;
        let geomWkt = element.geom;
        let cartesian3_str_list = geomWkt
          .replace("POLYGON((", "")
          .replace("))", "")
          .replaceAll(" ", ",")
          .split(",");
        let cartesian3_num_list = cartesian3_str_list.map((e) => {
          return parseFloat(e);
        });

        viewer.entities.add({
          name: "",
          polygon: {
            hierarchy: Cesium.Cartesian3.fromDegreesArray(cartesian3_num_list),
            material: imgPath,
            zIndex: index,
            width: 2,
          },
        });
      });
    });

    ipcRenderer.on("draw", () => {
      this.draw(viewer);
    });
  },

  methods: {
    draw(viewer) {
      // 绘制线条工具函数
      let drawing_polyline = (cartesian3_points_collection) => {
        if (viewer.entities.getById("polyline")) {
          viewer.entities.removeById("polyline");
        }

        viewer.entities.add({
          id: "polyline",
          polyline: {
            positions: cartesian3_points_collection,
            clampToGround: true,
            width: 1,
            material: Cesium.Color.fromBytes(156, 26, 26, 255),
          },
        });
      };

      // 绘制面工具函数
      let drawing_polygon = (cartesian3_points_collection) => {
        if (viewer.entities.getById("polygon")) {
          viewer.entities.removeById("polygon");
        }

        viewer.entities.add({
          id: "polygon",
          polygon: {
            hierarchy: cartesian3_points_collection,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            fill: true,
            material: Cesium.Color.WHITE.withAlpha(0.05),
            outline: true,
            outlineColor: Cesium.Color.RED,
            outlineWidth: 1,
          },
        });
      };

      // 初始坐标集合
      let static_points_collection = [];
      let dynamic_points_collection = [];
      let handler = viewer.screenSpaceEventHandler;
      //鼠标左键
      handler.setInputAction((le) => {
        let left_click_cartesian3_position = viewer.scene.pickPosition(
          le.position
        );
        if (Cesium.defined(left_click_cartesian3_position)) {
          static_points_collection.push(left_click_cartesian3_position);
          let polygon_callback = new Cesium.CallbackProperty(() => {
            return new Cesium.PolygonHierarchy(dynamic_points_collection);
          }, false);
          let polyline_callback = new Cesium.CallbackProperty(() => {
            return dynamic_points_collection;
          }, false);
          drawing_polygon(polygon_callback);
          drawing_polyline(polyline_callback);
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

      // 鼠标移动
      handler.setInputAction((movement) => {
        let move_end_cartesian3_position = viewer.scene.pickPosition(
          movement.endPosition
        );

        if (Cesium.defined(move_end_cartesian3_position)) {
          if (static_points_collection.length > 0) {
            dynamic_points_collection = static_points_collection.concat([
              move_end_cartesian3_position,
            ]);
          }
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

      // 鼠标右键
      handler.setInputAction(() => {
        if (static_points_collection.length > 2) {
          if (viewer.entities.getById("polygon")) {
            viewer.entities.removeById("polygon");
          }
          if (viewer.entities.getById("polyline")) {
            viewer.entities.removeById("polyline");
          }
          handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
          handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
          drawing_polygon(
            new Cesium.PolygonHierarchy(static_points_collection)
          );
          static_points_collection.push(dynamic_points_collection[0]);
          drawing_polyline(static_points_collection);

          let coordinates = "";
          for (let i = 0; i < static_points_collection.length; i++) {
            let coord_rad = viewer.scene.globe.ellipsoid.cartesianToCartographic(
              static_points_collection[i]
            );
            coordinates =
              coordinates +
              Cesium.Math.toDegrees(coord_rad.longitude).toFixed(5).toString();
            coordinates =
              coordinates +
              " " +
              Cesium.Math.toDegrees(coord_rad.latitude).toFixed(5).toString();
            coordinates = coordinates + ",";
          }

          coordinates = coordinates.substr(0, coordinates.length - 1);
          this.$store.commit("changeCoordinates", coordinates);
        }
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    },
  },
};
</script>

<style lang="scss" scoped>
#indexMap {
  width: 100%;
  height: 80%;
  background-color: #2b2b2b;
  flex: 2;
  #map {
    height: 100%;
    width: 100%;
  }
}
</style>
